var fs = require("fs");
var path = require("path");
var multer = require('multer')

// 递归创建目录 异步方法  
function mkdirs(dirname, callback) {
    fs.exists(dirname, function(exists) {
        if (exists) {
            callback();
        } else {
            // console.log(path.dirname(dirname));  
            mkdirs(path.dirname(dirname), function() {
                fs.mkdir(dirname, callback);
                console.log('在' + path.dirname(dirname) + '目录创建好' + dirname + '目录');
            });
        }
    });
}

// 递归创建目录 同步方法
function mkdirsSync(dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
}

function isExists(dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        return false;
    }
}

function upload(file, dirname, $new_filename, module_name) {
    var uploadFolder = path.join(global.UPLOAD_PATH, module_name);
    mkdirsSync(uploadFolder)

    // 通过 filename 属性定制
    var storage = multer.diskStorage({
        destination: function(req, file, cb) {
            cb(null, uploadFolder); // 保存的路径，备注：需要自己创建
        },
        filename: function(req, file, cb) {
            // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
            cb(null, file.fieldname + '-' + Date.now());
        }
    });

    // 通过 storage 选项来对 上传行为 进行定制化
    var upload = multer({ storage: storage })

}

function getUrl(filename, module_name = '') {

    if (module_name) {
        module_name = module_name + '/'
    }
    return '/uploads/' + module_name + filename
}


module.exports = {
    mkdirs: mkdirs,
    mkdirsSync: mkdirsSync,
    isExists: isExists,
    getUrl: getUrl
}